<template>
  <!-- 指标组件 -->
  <div class="barChart" v-loading="loading">
    <div class="barChart-title">
      <span>{{ data.name }}</span>
    </div>
    <div class="barChart-date">
      <!-- 日期 -->
      <p v-if="screenTime && screenTime.length != 0">
        <span class="left">{{ new Date(screenTime[0]).format("yyyy-MM-dd") }} ~ {{ new Date(screenTime[1]).format("yyyy-MM-dd") }}</span>
      </p>
      <p v-else>
        <span v-if="data.relativelyTime || data.relativelyTime == 0" class="left">{{ relativelyTimeDeal.format("yyyy-MM-dd") }} ~ {{ new Date().format("yyyy-MM-dd") }}</span>
        <span v-else class="left">{{ new Date(data.startTime).format("yyyy-MM-dd") }} ~ {{ new Date(data.endTime).format("yyyy-MM-dd") }}</span>
      </p>
      <!-- el-tooltip -->
      <p class="tooltip-p" v-if="screenTime && screenTime.length != 0">
        <el-tooltip content="筛选时段" placement="bottom" effect="light">
          <img class="right" :src="dateIcon" alt="">
        </el-tooltip>
      </p>
      <p class="tooltip-p" v-else>
        <el-tooltip v-if="data.relativelyTime || data.relativelyTime == 0" :content="`统计时段 相对${ data.relativelyTime/3600/1000/24 == 0 ? '今' : data.relativelyTime/3600/1000/24 }天时段`" placement="bottom" effect="light">
          <img class="right" :src="dateIcon" alt="">
        </el-tooltip>
        <el-tooltip v-else content="统计时段 固定时段" placement="bottom" effect="light">
          <img class="right" :src="dateIcon" alt="">
        </el-tooltip>
      </p>
    </div>
    <!-- tabs -->
    <div class="barChart-tabs" v-if="multipleData && multipleData.length != 0">
      <el-radio-group v-model="radio" size="mini" @change="handleChangeRadio">
        <el-radio-button 
          :label="item.chnVal"
          v-for="(item, index) in multipleData"
          :key="index"
        ></el-radio-button>
      </el-radio-group>
      <!-- <el-button size="mini" plain style="height: 26px;">{{ multipleData[0].chnVal }}</el-button> -->
    </div>
    <div style="width: 100%;height: 34px;" v-else>
    </div>
    <!-- echarts -->
    <div v-if="payloadData.dayData && payloadData.dayData.length != 0 && isScreenComplete" :id="'barCharts' + id" class="barChart-echarts" style="width: 100%;height: 272px;"></div>
    <!-- empty -->
    <el-empty v-else :image="emptyImg" description="暂无数据" :image-size="80" style="width: 100%;height: 272px;"></el-empty>
    <!-- 数据筛选dialog -->
    <OpenDataScreenDialog
      v-model:visible="openDataScreenVisible"
      v-model:dataOptions="dataOptions"
      @handleScreen="handleScreen">
    </OpenDataScreenDialog>
  </div>
</template>

<script>
// vuex
import store from "@/store";
// 图片
import dateIcon from '@/assets/dataCenter/dataB_dateIcon.png';
import * as echarts from 'echarts';
import emptyImg from '@/assets/dataCenter/dataB_empty.png';
// API
import {
  dataBoardByChartId,
  dataBoardMerchantGetChatData
} from '@/api/dataCenter/dataBoard.js';
// utils
import { dateStrChangeTimeTamp } from './utils.js'
// 组件
import OpenDataScreenDialog from './openDataScreenDialog.vue';
export default {
  name: 'BarChart',
  components: {
    OpenDataScreenDialog
  },
  props: {
    id: {
      type: Number,
      default: () => {
        return null;
      }
    }
  },
  data() {
    return {
      dateIcon,
      emptyImg,
      data: {},
      payloadData: {},
      multipleData: [],
      relativelyTimeDeal: null,
      loading: false,
      openDataScreenVisible: false,
      dataOptions: [],
      xAxisData: [],
      isScreenComplete: true
    }
  },
  watch: {
    screenTime: {
      handler(val) {
        this.dataBoardMerchantGetChatDataApi();
      },
      deep: true
    },
    organizationId: {
      handler(val) {
        this.dataBoardMerchantGetChatDataApi();
      },
      deep: true
    },
    openDataScreen: {
      handler(val) {
        if(val === this.id) {
          this.openDataScreenVisible = true
        }
      },
      deep: true
    }
  },
  mounted() {
    this.dataBoardByChartIdApi();
  },
  methods: {
    // 筛选数据
    handleScreen(val) {
      this.isScreenComplete = false;
      let legendData = [];
      val.forEach(item => {
        legendData.push(item.name);
      })
      // 通过事件循环极致更新视图
      setTimeout(() => {
        this.isScreenComplete = true;
        // 再次更新界面图表
        this.$nextTick(() => {
          this.drawCharts(this.xAxisData, legendData, val);
        })
      }, 10)
    },
    // 获取报表数据
    async dataBoardByChartIdApi() {
      let res = await dataBoardByChartId({
        id: this.id
      });
      if(res.code === 200) {
        this.data = res.payload;
        let start = new Date()
        start.setTime(start.getTime() - this.data.relativelyTime)
        this.relativelyTimeDeal = start;
        if(this.data.relativelyTime === 0) {
          this.relativelyTimeDeal = new Date();
        }
        // 获取chart数据
        this.dataBoardMerchantGetChatDataApi();
      }
    },
    // 获取报表具体数据
    async dataBoardMerchantGetChatDataApi() {
      this.loading = true;
      let startTime;
      let endTime;
      let screenTime = store.state.user.screenTime;
      if(screenTime && screenTime.length != 0) {
        startTime = dateStrChangeTimeTamp(screenTime[0]);
        endTime = dateStrChangeTimeTamp(screenTime[1]);
      } else {
        // startTime 和 endTime存在即固定时间
        if(this.data.startTime && this.data.endTime) {
          startTime = this.data.startTime;
          endTime = this.data.endTime;
        }
        // relativelyTime存在即相对时间
        if(this.data.relativelyTime) {
          let nowDate = new Date().getTime();
          console.log(nowDate, '222');
          let startDate = nowDate - this.data.relativelyTime;
          startTime = startDate;
          endTime = nowDate;
        }
      }
      let res = await dataBoardMerchantGetChatData({
        id: this.id,
        startTime,
        endTime,
        insId: store.state.insId.insId
      })
      if(res.code === 200) {
        this.payloadData = res.payload;
        if(this.payloadData && this.payloadData.dayData.length != 0)  {
          this.capsulationDealData(0);
        } else {
          this.loading = false;
        }
      }
    },
    // 处理数据封装
    capsulationDealData(currentIndex) {
      let dataKeyName;
      let dataValueName;
      let xAxisData = [];
      let legendData = [];
      let seriesData = [];
      if(this.payloadData.groupColumn && this.payloadData.groupColumn.indexOf('columnHumpName') != -1) {
        // 1、分组
        let groupColumn = JSON.parse(this.payloadData.groupColumn.replace(/\\/g, ''));
        dataValueName = groupColumn[0].columnHumpName;
        if(this.payloadData.specialColumn && this.payloadData.specialColumn.indexOf(',') != -1) {
          return
          // 多指标
          console.log('enter 分组多指标')
          this.multipleData = [];
          let dealSpecialColumn = this.payloadData.specialColumn.replace('{', '').replace('}', '').split(', ');
          dealSpecialColumn.forEach(item => {
            let obj = {};
            obj.enVal = item.split('=')[0];
            obj.chnVal = item.split('=')[1];
            this.multipleData.push(obj);
          })
          console.log('this.multipleData', this.multipleData)
          // 默认选
          this.radio = this.multipleData[currentIndex].chnVal;
          dataKeyName = this.multipleData[currentIndex].enVal;
          // Step1
          let dayData = [];
          this.payloadData.dayData.forEach(item => {
            let obj = {};
            obj.date = new Date(item.createTime).format("yyyy-MM-dd");
            obj.value = JSON.parse(item.dayData.replace(/\\/g, ''));
            dayData.push(obj);
          });
          console.log('dayData', dayData)
          // Step2
          dayData.forEach((item, index) => {
            if(index === 0) {
              item.value.forEach(val => {
                for(let i in val) {
                  if(String(dataValueName) === String(i)) {
                    legendData.push(val[i])
                  }
                }
              })
            }
            xAxisData.push(item.date);
          })
          // Step3
          legendData.forEach(item => {
            let obj = {
              name: item,
              type: 'bar',
              barWidth: '2%',
              data: []
            }
            dayData.forEach(val1 => {
              val1.value.forEach(val2 => {
                if(String(item) === val2[dataValueName]) {
                  for(let i in val2) {
                    if(String(dataKeyName) === String(i)) {
                      obj.data.push(val2[i]);
                    }
                  }
                }
              })
            })
            seriesData.push(obj);
          })
          console.log(xAxisData, seriesData, legendData)
        } else {
          // 单指标
          console.log('enter 分组单指标')
          this.multipleData = [];
          let dealSpecialColumn = this.payloadData.specialColumn.replace('{', '').replace('}', '').split(', ');
          dealSpecialColumn.forEach(item => {
            let obj = {};
            obj.enVal = item.split('=')[0];
            obj.chnVal = item.split('=')[1];
            this.multipleData.push(obj);
          })
          console.log('this.multipleData', this.multipleData)
          // 默认选
          this.radio = this.multipleData[currentIndex].chnVal;
          dataKeyName = this.multipleData[currentIndex].enVal;
          // Step1
          let dayData = [];
          this.payloadData.dayData.forEach(item => {
            let obj = {};
            obj.date = new Date(item.createTime).format("yyyy-MM-dd");
            obj.value = JSON.parse(item.dayData.replace(/\\/g, ''));
            dayData.push(obj);
          });
          console.log('dayData', dayData);
          // Step2
          dayData.forEach((item, index) => {
            if(index === 0) {
              item.value.forEach(val => {
                for(let i in val) {
                  if(String(dataValueName) === String(i)) {
                    legendData.push(val[i])
                  }
                }
              })
            }
            xAxisData.push(item.date);
          })
          // Step3
          legendData.forEach(item => {
            let obj = {
              name: item,
              type: 'bar',
              barWidth: '2%',
              data: []
            }
            dayData.forEach(val1 => {
              val1.value.forEach(val2 => {
                if(String(item) === val2[dataValueName]) {
                  for(let i in val2) {
                    if(String(dataKeyName) === String(i)) {
                      obj.data.push(val2[i]);
                    }
                  }
                }
              })
            })
            seriesData.push(obj);
          })
          console.log(xAxisData, seriesData, legendData)
        }
      } else {
      // 2、不分组
        if(this.payloadData.specialColumn && this.payloadData.specialColumn.indexOf(',') != -1) {
          // 多指标
          console.log('enter 不分组多指标')
          this.multipleData = [];
          let dealSpecialColumn = this.payloadData.specialColumn.replace('{', '').replace('}', '').split(', ');
          dealSpecialColumn.forEach(item => {
            let obj = {};
            obj.enVal = item.split('=')[0];
            obj.chnVal = item.split('=')[1];
            this.multipleData.push(obj);
          })
          console.log('this.multipleData', this.multipleData)
          // 默认选
          this.radio = this.multipleData[currentIndex].chnVal;
          dataKeyName = this.multipleData[currentIndex].enVal;
          // Step1
          let dayData = [];
          this.payloadData.dayData.forEach(item => {
            let obj = {};
            obj.date = new Date(item.createTime).format("yyyy-MM-dd");
            obj.value = JSON.parse(item.dayData.replace(/\\/g, ''));
            dayData.push(obj);
          });
          console.log('dayData', dayData)
          // Step2
          this.multipleData.forEach(item => {
            legendData.push(item.chnVal);
          })
          dayData.forEach(item => {
            xAxisData.push(item.date);
          })
          this.multipleData.forEach(item => {
            let obj = {
              name: item.chnVal,
              type: 'bar',
              barWidth: '2%',
              data: []
            }
            dayData.forEach(val1 => {
              val1.value.forEach(val2 => {
                for(let i in val2) {
                  if(String(item.enVal) === String(i)) {
                    obj.data.push(val2[i]);
                  }
                }
              })
            })
            seriesData.push(obj);
          })
          // 置空multipleData
          this.multipleData = [];
          console.log(xAxisData, seriesData, legendData)
        } else {
          // 单指标
          console.log('enter 不分组单指标')
          let specialColumn = this.payloadData.specialColumn.replace('{', '').replace('}', '').split('=');
          let dayData = [];
          this.payloadData.dayData.forEach(item => {
            console.log('item.dayData', item.dayData)
            let obj = {};
            obj.date = new Date(item.createTime).format("yyyy-MM-dd");
            obj.value = JSON.parse(item.dayData.replace(/\\/g, ''));
            dayData.push(obj);
          });
          console.log('dayData', dayData)
          seriesData = [
            {
              name: specialColumn[1],
              type: 'bar',
              barWidth: '2%',
              data: []
            }
          ]
          dayData.forEach(item => {
            xAxisData.push(item.date);
            seriesData[0].data.push(item.value[0][specialColumn[0]]);
          })
          legendData.push(specialColumn[1]);
          console.log(xAxisData, seriesData, legendData)
        }
      }
      this.loading = false;
      this.$nextTick(() => {
        if(this.payloadData.dayData.length != 0) {
          this.drawCharts(xAxisData, legendData, seriesData);
          console.log('drawCharts', xAxisData, legendData, seriesData);
          this.xAxisData = xAxisData;
          // 数据筛选数据源
          this.dataOptions = seriesData;
        }
      })
    },
    drawCharts(xAxisData, legendData, seriesData) {
      let myChart = echarts.init(document.getElementById('barCharts' + this.id));
      let option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: legendData
        },
        grid: {
          left: '1%',
          right: '1%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: xAxisData,
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: seriesData
      };
      myChart.setOption(option);
      window.addEventListener('resize', () => {
        if(myChart) myChart.resize();
      })
    }
  },
  computed: {
    screenTime() {
      return store.state.user.screenTime;
    },
    organizationId() {
      return store.state.insId.insId;
    },
    openDataScreen() {
      return store.state.user.openDataScreen;
    }
  }
}
</script>

<style lang="scss" scoped>
.barChart {
  width: 100%;
  height: 100%;
  &-title {
    width: 100%;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    span {
      color: #252934;
      height: 24px;
      // width: 112px;
      font-family: PingFangSC-Medium;
      font-size: 16px;
      line-height: 24px;
      cursor: pointer;
    }
  }
  &-date {
    width: 100%;
    height: 16px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    // margin-bottom: 34px;
    .left {
      font-size: 12px;
      color: #6b798e;
    }
    .right {
      margin-left: 18px;
    }
    .tooltip-p {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  &-tabs {
    width: 100%;
    height: 34px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }
  &-echarts {
    width: 100%;
    height: 42px;
    
  }
}
</style>

<style lang="scss">
.barChart {
  .el-radio-button__inner {
    padding: 6px 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
  }
}
</style>